<?php
/**
 * Centraliza o controle de autenticação
 * @author Renato Lenz @ PC4 Team
 *
 */
class PC4_Controlador_Plugin_Auth extends Zend_Controller_Plugin_Abstract
{
	public
		$modulosAutenticados,
		$urlLogin;
	
	public function __construct($modulosAutenticados = array('admin'), $urlLogin = null) {
		$this->modulosAutenticados = $modulosAutenticados;
	}
		
    /**
     * Predispatch method to authenticate user
     *
     * @param Zend_Controller_Request_Abstract $request
     */
    public function preDispatch(Zend_Controller_Request_Abstract $request)
    {
        //user only to login for access to admin functions
        if (
        	!in_array($request->getModuleName(), $this->modulosAutenticados)
        	|| $request->getControllerName() == 'login'
        ) {
            return;
        }

        // checa a autenticação
	    $auth = Zend_Auth::getInstance();
		if ($auth->hasIdentity()) {
		    $identity = $auth->getIdentity();
		    
		    $this->init($identity);

		    return;
		}
         
        /**
         * User not logged in or not allowed to access admin ... redirect to login.
         * Note: if user is logged in but not authorised, we redirect to login
         * to allow user to login as a different user with the right permissions.
         */
		$redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
		
		if (empty($this->urlLogin)) {
			$this->urlLogin = $request->getModuleName() . '/login';
		}
		$redirector->gotoUrl($this->urlLogin)->redirectAndExit();
    }
    
    protected function init($identity) {
        // pega a instância do layout
        $layout = Zend_Layout::getMvcInstance();
	    // coloca a identidade no layout
        $layout->identity = $identity;
    }
}